package com.google.code.mukiranaproject.netlib;

import java.util.ArrayList;

import javax.swing.text.MutableAttributeSet;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLEditorKit;

import com.google.code.mukiranaproject.model.Lance;

public class LancesParserCallback extends HTMLEditorKit.ParserCallback {

	private final static String USER_DIV_ID = "lastbids-user";
	private final static String VALOR_DIV_ID = "lastbids-value";
	
	private boolean mainDivTag = false;
	private boolean userDiv = false;
	private boolean valorDiv = false;
	
	private String lastBidsDivId;
	private String idLeilao;
	private ArrayList<Lance> lances;
	private Lance lance;

	public LancesParserCallback(String id, String idLeilao) {
		this.lastBidsDivId = id;
		this.idLeilao = idLeilao;
		lances = new ArrayList<Lance>();
	}
	
	public void handleStartTag(HTML.Tag tag, MutableAttributeSet attributes, int pos) {
		if (tag == HTML.Tag.DIV) {
			String value = (String) attributes.getAttribute(HTML.Attribute.ID);
			if ((value != null) && value.equalsIgnoreCase(lastBidsDivId)) {
				mainDivTag = true;
			}
			
			value = (String) attributes.getAttribute(HTML.Attribute.CLASS);
			if ((value != null) && value.equalsIgnoreCase(USER_DIV_ID)) {
				userDiv = true;
			}
			
			if ((value != null) && value.equalsIgnoreCase(VALOR_DIV_ID)) {
				valorDiv = true;
			}
		}
	}
	
	public void handleText(char [] data, int pos) {		
		if (userDiv) {
			lance = new Lance();
			lance.setUsuario(new String(data));
			lance.setLeilao(idLeilao);
		}
		
		if (valorDiv) {
			String centavosStr = new String(data);
			lance.setCentavos(treatValor(centavosStr));
			lances.add(lance);
		}
	}
	
	private long treatValor(String valorStr) {
		valorStr = valorStr.replace(",","");
		valorStr = valorStr.replace("R$ ", "");
		return Long.parseLong(valorStr);
	}
	
	public void handleEndTag(HTML.Tag tag, int pos) {
		if (mainDivTag && !userDiv && !valorDiv) {
			if (tag == HTML.Tag.DIV) {
				mainDivTag = false;
			}
		}
		
		if (userDiv) {
			if (tag == HTML.Tag.DIV) {
				userDiv = false;
			}
		}
		
		if (valorDiv) {
			if (tag == HTML.Tag.DIV) {
				valorDiv = false;
			}
		}
	}
	
	public Lance getLance() {
		return this.lance;
	}
	
	public ArrayList<Lance> getLances() {
		return this.lances;
	}
}
